<template>
  <div class="auth">
    <h2>注册</h2>
    <form @submit.prevent="register">
      <input v-model="name" placeholder="用户名" required />
      <input v-model="email" placeholder="邮箱" type="email" required />
      <input v-model="password" placeholder="密码" type="password" required />
      <input v-model="password_confirmation" placeholder="确认密码" type="password" required />
      <button type="submit">注册</button>
    </form>

    <p style="margin-top: 10px">
      已有账号？
      <router-link to="/login">登录</router-link>
    </p>

    <p v-if="message" style="color:green">{{ message }}</p>
    <p v-if="error" style="color:red">{{ error }}</p>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import authApi from '../api/auth'
import { useRouter } from 'vue-router'

const name = ref('')
const email = ref('')
const password = ref('')
const password_confirmation = ref('')
const message = ref('')
const error = ref('')
const router = useRouter()

const register = async () => {
  try {
    await authApi.register({
      name: name.value,
      email: email.value,
      password: password.value,
      password_confirmation: password_confirmation.value
    })
    message.value = '注册成功，请登录'
    setTimeout(() => router.push('/login'), 1000)
  } catch (err) {
    error.value = err.response?.data?.message || '注册失败'
  }
}
</script>
